<?php

ini_set('display_errors', 1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';

use Biz\model\brandAccount\BrandAccountAuth;
use Biz\model\brandAccount\BrandAccountInfo;

$id = $argv[1] ?? '';
$list = [];
$page = 1;
do {
    $where = ['LIMIT' => [($page - 1) * 20, 20], 'account_status[!]' => BrandAccountInfo::ACCOUNT_STATUS_DEL];
    if ($id) {
        $where['id'] = $id;
    }
    $list = BrandAccountInfo::select('*', $where);
    $today = date('Y-m-d');
    foreach ($list as $account) {
        $accountId = $account['id'];
        $accountData = [];
        $authList = BrandAccountAuth::getAllByWhere(['account_id' => $accountId, 'ORDER' => ['id' => 'DESC']]);
        $usedAuthInfo = [];
        if (count($authList) == 1) {
            $usedAuthInfo = $authList[0];
        } else {
            foreach ($authList as $row) {
                if ($row['auth_status'] == BrandAccountAuth::AUTH_STATUS_USED) {
                    $usedAuthInfo = $row;
                    break;
                }
            }
            if (empty($usedAuthInfo)) {
                foreach ($authList as $row) {
                    if ($row['auth_status'] == BrandAccountAuth::AUTH_STATUS_PASS) {
                        $usedAuthInfo = $row;
                        break;
                    }
                }
            }
            if (empty($usedAuthInfo)) {
                $usedAuthInfo = $authList[0];
            }
        }
        if ($account['account_status'] == BrandAccountInfo::ACCOUNT_STATUS_USED && $usedAuthInfo) {
            BrandAccountAuth::update(['auth_status' => BrandAccountAuth::AUTH_STATUS_USED], ['account_id' => $accountId, 'id' => $usedAuthInfo['id']]);
            BrandAccountAuth::update(['auth_status' => BrandAccountAuth::AUTH_STATUS_EXPIRE], [
                'account_id' => $accountId,
                'id[!]' => $usedAuthInfo['id'],
                'auth_status' => BrandAccountAuth::AUTH_STATUS_PASS
            ]);
        } else if ($account['account_status'] == BrandAccountInfo::ACCOUNT_STATUS_EXPIRE) {
            BrandAccountAuth::update(['auth_status' => BrandAccountAuth::AUTH_STATUS_EXPIRE], [
                'account_id' => $accountId,
                'auth_status' => BrandAccountAuth::AUTH_STATUS_PASS
            ]);
        }
    }
    $page++;
} while ($list);

